package com.itheima.wemedia.service.impl;

import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.AppJwtUtil;
import com.itheima.wemedia.pojo.WmUser;
import com.itheima.wemedia.mapper.WmUserMapper;
import com.itheima.wemedia.service.WmUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @description <p>自媒体用户信息 业务实现</p>
 *
 * @version 1.0
 * @package com.itheima.wemedia.service.impl
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    
    /**
     * 通过ap_user.id查询自媒体用户信息
     * @param apUserId
     * @return
     */
    @Override
    public WmUser findByApUserId(Long apUserId) {
        return query().eq("ap_user_id",apUserId).one();
    }

    /**
     * 登录校验
     * @param loginParam
     * @return
     */
    @Override
    public Map<String, Object> loginCheck(Map<String, String> loginParam) {
        //1. 获取参数
        String name = loginParam.get("name");
        String password = loginParam.get("password");
        //2. 参数非空校验
        if(StringUtils.isEmpty(name) || StringUtils.isEmpty(password)){
            throw new LeadNewsException("用户名或密码错误!");
        }
        //3. 通过登录名查询用户信息
        WmUser wmUser = query().eq("name", name).one();
        if(null == wmUser){
            // 查不到数据则报错
            throw new LeadNewsException("用户名或密码错误!");
        }
        //4. 密码校验
        //4.1 密码加盐后进行MD5
        password += wmUser.getSalt();
        String encryptedPwd = DigestUtils.md5DigestAsHex(password.getBytes());
        //4.2 校验密码是否相同，不同则报错
        if(!wmUser.getPassword().equals(encryptedPwd)){
            throw new LeadNewsException("用户名或密码错误!");
        }
        //5. 校验通过，生成token令牌
        String token = AppJwtUtil.createToken(wmUser.getId().longValue());
        //6. 构建结果并返回
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("user", wmUser);
        return result;
    }
}
